package com.atguigu.spark.util.kafka

import com.atguigu.spark.util.util.PropUtil
import org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord}
import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.InputDStream
import org.apache.spark.streaming.kafka010.{ConsumerStrategies, KafkaUtils, LocationStrategies}
import org.apache.spark.streaming.{Duration, StreamingContext}

object Kafka_Consumer {
  def main(args: Array[String]): Unit = {
    val ssc: StreamingContext = new StreamingContext(new SparkConf().setMaster("local[*]")
      .setAppName("spark-streaming")
      .set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
      .set("spark.testing.memory", "2147480000"), Duration.apply(3000))

    val kafkaPara: Map[String, Object] = Map[String, Object](
      ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG -> PropUtil("kafka.brokers"),
      ConsumerConfig.GROUP_ID_CONFIG -> PropUtil("kafka.group"),
      "key.deserializer" -> "org.apache.kafka.common.serialization.StringDeserializer",
      "value.deserializer" -> "org.apache.kafka.common.serialization.StringDeserializer"
    )
    val kafkaDStream: InputDStream[ConsumerRecord[String, String]] = KafkaUtils
      .createDirectStream[String, String](ssc, LocationStrategies.PreferConsistent,
        ConsumerStrategies.Subscribe[String, String](Set(PropUtil("kafka.topic")), kafkaPara))
    kafkaDStream.map(_.value()).print()
    ssc.start()
    ssc.awaitTermination()
    ssc.stop()
  }
}
